from collections import defaultdict
import pymongo
import time
import json
import requests
import redis
from wxpy import Bot, Group, TEXT, Tuling
from datetime import date, timedelta

# 127
client_127 = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
db_127 = client_127.cs_recharge
coll_127 = db_127.rechange
conn = redis.Redis()

bot = Bot(console_qr=2, cache_path="botoo.pkl")
groups = bot.groups()
group = None
for i in groups:
    if i.name == '127星恒太':
        group = i
if not group:
    print("找不到群")


def get_ts():
    return str(time.time()).replace('.', '')[:13]


def get_unknow():
    res = defaultdict(int)
    today = date.today()
    today = today.strftime('%Y%m%d')
    # 127
    count_close = conn.get("close_ctcc_no")
    # count = if countcount.decode()
    if count_close:
        count_close = int(count_close.decode())
    else:
        count_close = 60
    unicom_9 = conn.smembers('ctcc_9')

    print("数量", conn.scard('ctcc_9'), count_close)
    if conn.scard('ctcc_9') > count_close:
        is_close = conn.get("is_ctcc_close")
        if is_close.decode() != '1':
            conn.set("is_ctcc_close", 1)
            group.send("电信未知总数量大于%s关闭交易" % count_close)

    amount = 0
    for order in unicom_9:
        order = order.decode()
        obj = coll_127.find_one({"ordernumber": order})
        if obj['orderdate'] != today:
            conn.srem('ctcc_9', order)
        elif obj['orderstate'] != '9':
            conn.srem('ctcc_9', order)
        else:
            amount += int(obj['amount'])
            prov = obj['prov']
            res[prov] += 1
            close_num = conn.hget("ctcc_prov_cnum", prov)
            if close_num:
                close_num = int(close_num.decode())
            else:
                close_num = 10
            if res[prov] > close_num:
                # print("联通%s未知总数量大于%s关闭交易" % (prov, res[prov]))
                if not conn.sismember('unused_ctcc_prov', prov):
                    group.send("电信%s未知总数量大于%s关闭交易" % (prov, close_num))
                    conn.sadd("unused_ctcc_prov", prov)

    for prov, count in res.items():
        close_num = conn.hget("ctcc_prov_cnum", prov)
        if close_num:
            close_num = int(close_num.decode())
        else:
            close_num = 5
        if count < close_num:
            if conn.sismember('unused_ctcc_prov', prov):
                conn.srem("unused_ctcc_prov", prov)

    res['未知笔数'] = sum(res.values())
    res["未知金额"] = amount
    return res


while True:
    now = time.time()
    try:

        res = get_unknow()
        print(time.time() - now)
        # s_c = conn.hget('ctcc_unkonw', "成功笔数")
        # s_s = conn.hget('ctcc_unkonw', "成功金额")
        # if s_c:
        #     s_c = int(s_c.decode())
        #     res['成功笔数'] = s_c
        # if s_s:
        #     s_s = int(s_s.decode())
        #     res['金额占比'] = "%4f" % (res['未知金额'] / (res['未知金额'] + s_s))
        #     res['成功金额'] = s_s
        print(res)
        conn.delete('ctcc_unkonw')
        conn.hmset("ctcc_unkonw", res)
    except Exception as e:
        print(e)

    # message = "; ".join(["%s:%s" % (k, v) for k, v in res.items()])
    # message = "各省未知数量：" + message
    # group.send(message)
    time.sleep(6)
